import React, { useRef, useEffect, useState } from 'react';
// import { Link } from 'react-router-dom';
import styles from './index.module.less';
import Tabs from '@/components/tabs';
import ApproveCard from '@/components/card';
// import { DocList } from '@/services/official-doc';
import { getMyTaskListApi, setTaskAction, setBatchTaskAction } from '@/services/approval';
import { isCheckedAuth, sendVerificationCode, checkVerificationCode } from '@/services/commons';
import ButtonFooterDetail from '@/components/button-footer-detail';
import { Toast, Modal } from 'antd-mobile-v2';
import { Prompt } from 'react-router-dom';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import EmptyLoading from '@/components/empty/empty-loading';
import ConfirmAndRefuseModal from '@/components/ConfirmAndRefuseModal';
import { applyType } from '@/constants';
import history from '@/utils/history';
// import { APPROVAL_STATUS } from '@/pages/declare/constants';
import checkedIcon from '@/assets/images/checked.png';
import uncheckedIcon from '@/assets/images/unChecked.png';
import VerificationCodeModal from '@/components/verification-code-modal';

interface DetailItem {
  innerProcDefId: string;
  applyName: string;
  procRecordId: string;
  applyId: string;
  applyType: string;
  applyUserId: string;
  crtTime: string;
  id: string;
  handler: string;
  procStatus: number;
  needSign: 0 | 1;
}

enum OperationsObj {
  CONFIRM = '0004',
  REFUSE = '0007'
}

// 视窗高度减去减去头部和底部组件的高度
const height = document.documentElement.clientHeight - document.documentElement.clientWidth * (40 + 5) / 375;
const defaultPageSize = 10;

const Log: React.FC<RouterProps> = (props) => {
  const menu = useRef([
    { text: '待审批', value: 1 },
    { text: '已审批', value: 2 }
  ]);

  const [pageSize, setPageSize] = useState(defaultPageSize);
  const [modalObj, setModalObj] = useState<any>({}); // 同意/拒绝的弹窗格式
  const [modalVisible, setModalVisible] = useState<boolean>(false); // 同意/拒绝的弹窗显示隐藏
  const [batchApprovalVisible, setBatchApprovalVisible] = useState<boolean>(false); // 批量审批样式显示隐藏
  const [from] = useState<string>('BatchApproval'); // 来源 批量审批页面
  const [approvalArr, setApprovalArr] = useState([]); // 批量审批数组
  const [selectAll, setSelectAll] = useState(false); // 是否全选
  const [unApprovaltotal, setUnApprovaltotal] = useState(0); // 未审批数量
  const [verificationCodeModalVisible, setVerificationCodeModalVisible] = useState<boolean>(false); // 短信验证弹窗显隐
  const [signType, setSignType] = useState<OperationsObj>();

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    initSearchData: { type: 1 }, // 待审批 1 已审批 2
    cacheRouteList: [
      '/declare/detail'
    ],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      const reqParams = {
        lastId: params.lastId,
        pageSize: params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize,
        operationType: params?.type,
        pageNum: 1
      };
      const res = await getMyTaskListApi(reqParams);
      const list = formatData(res.data?.list) || [];
      setSurplusTotal(res.data?.total ?? 0);
      setPageSize(params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize);
      setData(params?.lastId ? dataSource.concat(list) : list);
      setLastId(list[list.length - 1]?.id);
    }
  });

  useEffect(() => {
    getDocListNum();
  }, []);

  // 获取未审批数量
  const getDocListNum = async () => {
    const data = {
      lastId: '',
      pageSize: 10,
      operationType: 1, // 待审批 1 已审批 2
      pageNum: 1
    };
    const res = await getMyTaskListApi(data);
    if (res?.data.total) { setUnApprovaltotal(res.data.total); }
  };

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      const formValues = item.formValues || item?.formData?.formValues;
      const jsonData = JSON.parse(formValues);
      switch (item.applyType) {
        case applyType.STOCK_RECEIVE_APPLY:
          item.formData = [
            { label: '划转批次', value: jsonData.lot?.text || '无' },
            {
              label: '业务名称',
              value: item.typeName || item.taskName || '无'
            },
            {
              label: '更新时间',
              value: item?.lastHandlerTime || item.crtTime || '无'
            }
          ];
          break;
        default:
          break;
      }
      item.cardTitle = item.applyName || item.procName || '无';
    });
    return data;
  };

  const handleJump2Detail = (item: any) => {
    if (banNextStep()) { return; }
    history.push({
      pathname: '/declare/detail',
      query: {
        applyType: item.applyType,
        innerProcDefId: item.innerProcDefId,
        procRecordId: item.procRecordId,
        applyId: item.applyId,
        // resubmit: item.status !== APPROVAL_STATUS.Draft ? true : false,
        title: item.applyName,
        status: item.procStatus,
        type: searchData?.type,
        taskRecordId: item.taskRecordId,
        needSign: item.needSign
      }
    });
  };

  //操作同意
  const handleOK = (item: DetailItem) => {
    if (banNextStep()) { return; }
    confirmHandle('0004', item);
  };

  //操作拒绝
  const handleRefuse = (item: DetailItem) => {
    if (banNextStep()) { return; }
    confirmHandle('0007', item);
  };

  const confirmHandle = async (optType: string, item: DetailItem) => {
    const needMessageCheck = await checkMessageAuth(item.needSign);
    if (needMessageCheck) {
      setVerificationCodeModalVisible(true);
    }
    if (optType === OperationsObj.CONFIRM) {
      setModalObj({
        btnWord: '确认同意',
        opreationTitle: `确定同意${item?.applyName}${item?.applyName.includes('申请') ? '吗？' : '申请吗？'}`,
        placeholder: '请输入审批意见（必填）',
        opreationType: optType,
        detailItem: item
      });
    } else {
      setModalObj({
        btnWord: '确认拒绝',
        opreationTitle: `确定拒绝${item?.applyName}${item?.applyName.includes('申请') ? '吗？' : '申请吗？'}`,
        placeholder: '请输入审批意见（必填）',
        opreationType: optType,
        detailItem: item
      });
    }
    setModalVisible(true);
  };

  const doClose = (val: boolean) => {
    setModalVisible(val);
  };

  const doSubmit = (val: boolean, word: string) => {
    modalOk(word, val);
  };

  const modalProps = {
    topTitle: '审批意见',
    modalVisible,
    doClose,
    doSubmit,
    ...modalObj
  };

  // 弹框确认
  const modalOk = async (formVal: string, show: boolean) => {
    const params = {
      action: modalObj?.opreationType,
      taskRecordId: modalObj?.detailItem?.id as string,
      handlerComment: formVal
    };
    try {
      const res: any = await setTaskAction(params);
      if (res.status == 200) {
        Toast.success('操作成功');
        setModalVisible(show);
        setDatasource(dataSource.filter((it) => it?.id !== modalObj?.detailItem?.id)); // 更新列表数据，不重新请求列表
        // if (dataSource?.length > 0) { setUnApprovaltotal(dataSource.length - 1); }
        getDocListNum();
      } else {
        Toast.success(res.message);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 展示/隐藏批量处理
  const handleShowBatchApprovalFn = () => {
    if (!batchApprovalVisible === false) {
      setApprovalArr([]);
    }
    setBatchApprovalVisible(!batchApprovalVisible);
    // renderRow重新渲染
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignores
    setDatasource([...dataSource]);
  };

  // 获取底部按钮
  const getButtonOptions = () => {
    // 批量审批
    if (batchApprovalVisible && searchData?.type === 1 && dataSource.length > 0) {
      return (
        [
          {
            text: selectAll ? '取消全选' : '全选',
            icon: <i className="iconfont icon">&#xe726;</i>,
            onClick: handleSelectAllFn
          },
          {
            text: '拒绝',
            icon: <i className="iconfont icon">&#xe717;</i>,
            onClick: () => batchApprovalFn(OperationsObj.REFUSE)
          },
          {
            text: '同意',
            icon: <i className="iconfont icon">&#xe718;</i>,
            onClick: () => batchApprovalFn(OperationsObj.CONFIRM)
          }
        ]
      );
    }
    return (
      [
        {
          text: '批量处理',
          icon: <i className="iconfont icon">&#xe714;</i>,
          onClick: handleShowBatchApprovalFn
        }
      ]
    );
  };

  // 选中需要批量审批的数据
  const selectApprovalFn = (itemData) => {
    const params = approvalArr;
    const index = params.findIndex((item) => item.id === itemData.id);
    if (index < 0) {
      params.push({ id: itemData.id, needSign: itemData.needSign });
    } else {
      params.splice(index, 1);
    }
    setApprovalArr(params);
    // renderRow重新渲染
    setDatasource([...dataSource]);
  };

  // 根据选中数据判断样式
  const getCheckedIcon = (itemData) => {
    const isExist = approvalArr.some((item) => (item.id === itemData.id));
    if (isExist) {
      return <img src={checkedIcon} alt="" />;// 选中按钮
    }
    return <img src={uncheckedIcon} alt="" />; // 未选中按钮
  };

  // 监听全选反选状态变化
  useEffect(() => {
    let params = approvalArr;
    // 取消全选，清空选中的数据
    if (!selectAll && dataSource.length === approvalArr.length) {
      setApprovalArr([]);
      setDatasource([...dataSource]);
      return;
    }
    // 点击全选，selectAll为true，选中所有数据
    if (selectAll) {
      dataSource.forEach((item: any) => {
        params.push({ id: item.id, needSign: item.needSign });
      });
    }
    // selectAll为false,不改变原来选中的数据
    if (!selectAll) {
      params = approvalArr;
    }
    const obj = {};
    const newParams = params.reduce((cur, next) => {
      obj[next.id] ? '' : obj[next.id] = true && cur.push(next);
      return cur;
    }, []); //设置cur默认类型为数组，并且初始值为空的数组
    setApprovalArr(newParams);
    setDatasource([...dataSource]);
  }, [selectAll]);

  // 监听dataSource变化
  useEffect(() => {
    if (dataSource.length != approvalArr.length) {
      setSelectAll(false);
    } else {
      setSelectAll(true);
    }
  }, [dataSource]);

  // 监听tab的切换
  useEffect(() => {
    if (searchData?.type === 2) {
      setBatchApprovalVisible(false);
      setApprovalArr([]);
    }
  }, [searchData?.type]);

  // 全选反选
  const handleSelectAllFn = () => {
    setSelectAll(!selectAll);
  };

  // 刷新页面清空选中数据
  const handleRefreshFn = () => {
    handleRefresh();
    setApprovalArr([]);
  };

  // 批量审批
  const batchApprovalFn = async (action) => {
    if (approvalArr.length === 0) {
      Toast.info('请选择需要审批的数据');
      return;
    }
    setSignType(action);
    const hasSign = approvalArr.some((itme) => itme.needSign === 1);
    const needMessageCheck = await checkMessageAuth(hasSign);
    if (needMessageCheck) {
      setVerificationCodeModalVisible(true);
    } else {
      doBatchApproval(action);
    }
  };
  const doBatchApproval = (action: OperationsObj) => {
    const params = [];
    if (approvalArr.length === 0) {
      Toast.info('请选择需要审批的数据');
      return;
    }
    approvalArr.forEach((item) => {
      params.push({
        action, // 类型 0004 同意 0007 拒绝
        taskRecordId: item.id
      });
    });
    const title = action === OperationsObj.CONFIRM
      ? `确定同意已选择的${params.length}个申请？`
      : `确定拒绝已选择的${params.length}个申请？`;
    Modal.alert(title, '', [
      { text: '取消', onPress: () => console.log('cancel'), style: 'default' },
      {
        text: '确认', onPress: async () => {
          Toast.loading('处理中', 0, null, true);
          try {
            const res: any = await setBatchTaskAction(params);
            if (res.status == 200) {
              Toast.hide();
              Toast.success('操作成功');
              setBatchApprovalVisible(false);
              setApprovalArr([]);
              handleRefresh();
              // if (dataSource?.length > 0) { setUnApprovaltotal(dataSource.length - approvalArr.length); }
              getDocListNum();
            } else {
              Toast.hide();
              setBatchApprovalVisible(false);
              setApprovalArr([]);
              Toast.info(res.message);
            }
          } catch (error) {
            console.log(error);
          }
        }
      }
    ]);
  };

  // 批量审批禁止其他操作
  const banNextStep = () => {
    if (searchData?.type === 1 && batchApprovalVisible) {
      return true;
    }
    return false;
  };

  const checkMessageAuth = async (needSign: 0 | 1 | boolean) => {
    // mock
    // needSign = 1;
    // mock end
    if (!needSign) return false;
    const res = await isCheckedAuth();
    if (!res.data) {
      return true;
    }
    return false;
  };

  const handleVerificationClose = () => {
    setVerificationCodeModalVisible(false);
    setModalVisible(false);
  };

  const handleVerifiSuccess = () => {
    console.log('signType-----------{}', signType);
    signType && doBatchApproval(signType);
    setVerificationCodeModalVisible(false);
  };

  const formatRenderRow = (item, sectionID, index) => {
    return (
      <div className={styles.cardItem} key={index}>
        {/* 批量审批按钮 */}
        {searchData?.type === 1 && batchApprovalVisible && (
          <div className={styles.selectBox}>
            <div className={styles.checkedBox} onClick={() => selectApprovalFn(item)}>
              {getCheckedIcon(item)}
            </div>
          </div>
        )}
        <div className={styles.cardItemBox} onClick={() => handleJump2Detail(item)}>
          <ApproveCard
            data={item}
            hasAvatar
            withStatus
            hasButton={searchData?.type === 1 ? true : false}
            onPass={() => handleOK(item)}
            onReject={() => handleRefuse(item)}
            from={from}
            BatchApprovalButtonStyle={batchApprovalVisible}
          >
          </ApproveCard>
        </div>
      </div>
    );
  };

  return (
    <div className={styles.wrap}>
      {/* 头部tab栏目 */}
      <div className={styles.bigWrapBox}>
        <div className={`${batchApprovalVisible && searchData?.type === 1 && styles.tabWrap}`}>
          {batchApprovalVisible && searchData?.type === 1 ? (
            <div className={styles.selectTabBox}>
              <div className={styles.cancelBtn} onClick={() => handleShowBatchApprovalFn()}>取消</div>
              <div className={styles.selectTabCountBox}>已选择{approvalArr.length}项</div>
            </div>
          ) :
            <Tabs total={unApprovaltotal} data={menu.current} dataType={searchData?.type} onChange={(value) => handleSearch({ type: value })} />
          }
        </div>
      </div>
      {
        showDom ?
          <div className={styles.cardList} id="leftPanel">
            {
              dataSource?.length > 0 ?
                <AntdRefreshList
                  height={height}
                  initialListSize={pageSize}
                  dataSource={dataSource}
                  refreshing={refreshing}
                  loadingMore={loadingMore}
                  renderRow={formatRenderRow}
                  onRefresh={handleRefreshFn}
                  onEndReached={handleLoadMore}
                  paddingBottomstyle={searchData?.type === 1}
                />
                : (
                  <EmptyRefresh
                    refreshing={refreshing}
                    onRefresh={handleRefreshFn}
                  />
                )
            }
            {searchData?.type === 1 && dataSource.length > 0 && (
              <ButtonFooterDetail
                from={from}
                data={getButtonOptions()}
              />
            )}
          </div>
          : <EmptyLoading />
      }
      <ConfirmAndRefuseModal {...modalProps} />
      <VerificationCodeModal
        visible={verificationCodeModalVisible}
        handleModalClose={handleVerificationClose}
        sendVerificationCode={sendVerificationCode}
        checkVerificationCode={checkVerificationCode}
        handleSuccess={handleVerifiSuccess}
        title={'身份验证'}
      />
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default Log;
